<?php
class PortsController extends AppController {

	var $name = 'Ports';

	function index() {
		$this->Port->recursive = 3;
		$this->set('ports', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid port', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('port', $this->Port->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Port->create();
			if ($this->Port->save($this->data)) {
				$this->Session->setFlash(__('The port has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The port could not be saved. Please, try again.', true));
			}
		}
		$units = $this->Port->Unit->find('list');
		$this->Port->Join->virtualFields =array('portname' => 'CONCAT(Unit.name,"-",Join.position,"-", Join.subid)'); # trick
		$options['fields']=array('id', 'portname');
		$options['joins']=array( array('table'=>'units','alias'=>'Unit', 'type'=>'LEFT', 'conditions'=>array('Join.unit_id = Unit.id')));
		$joins = array(''=>'');
		$joins[] = $this->Port->Join->find('list',$options);
	
		$this->set(compact('units', 'joins'));
	}

	function edit($id = null) {

		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid port', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Port->save($this->data)) {
				$this->Session->setFlash(__('The port has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The port could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Port->read(null, $id);
		}
		$units = $this->Port->Unit->find('list');
		$this->Port->Join->virtualFields =array('portname' => 'CONCAT(Unit.name,"-",Join.position,"-", Join.subid)'); # trick
		$options['fields']=array('id', 'portname');
		$options['joins']=array( array('table'=>'units','alias'=>'Unit', 'type'=>'LEFT', 'conditions'=>array('Join.unit_id = Unit.id')));
		$joins = array(''=>'');
		$joins[] = $this->Port->Join->find('list',$options);
		$this->set(compact('units', 'joins'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for port', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Port->delete($id)) {
			$this->Session->setFlash(__('Port deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Port was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
?>